var page = 1;           //当前页
var perPage = 10;       //每页显示的数据条数
var totalPage = 1;      //最大页码
var studentsList;       //学生列表信息
var totalCount = 10;    //总的学生数量
var index = 0;      //页面显示哪一项

/*
    主流程，给页面添加监听，在基本内容加载完成后，开始按照参数加载不同的内容
 */
document.addEventListener("DOMContentLoaded", function() {
    //设置页面的初始参数
    configPage();
    //创建默认的页面元素
    createContentArea();
    //顶部导航区域的点击事件绑定
    addEventToTopArea();
    //底部区域页码的点击事件绑定
    addEventToPageArea();
    //加载完页面后，进行网络请求等操作
    onLoadContent();
});

//获取页面的链接中的参数，标记当前应该加载什么资源
function configPage() {
    const params = new URLSearchParams(window.location.search);
    var urlIndex = params.get('index');
    if (urlIndex == null) index = 0;
    else index = Number(urlIndex);
    //设置导航条下的页面标题
    var title = document.getElementById("contentTitle");
    if (index === 0) {
        title.textContent = "学生信息列表";
    }
    else if (index === 1) {
        title.textContent = "新增学生信息";
    }
    else if (index === 2) {
        title.textContent = "查找学生信息";
    }
    else if (index === 3) {
        title.textContent = "管理员信息";
    }
}

//根据页面index不同加载不同的内容
function createContentArea() {
    if (index === 0 || index === 2) {
        //学生列表的表头
        createStudentTableHeader();
    }
    else if (index === 1) {
        //新增学生页面
        createNewStudentArea();
    }
    else if (index === 3) {
        //管理员页面
        createDBUserArea([]);
    }
}

//在其它流程执行完毕后，视页面不同进行网络请求、数据刷新等操作
function onLoadContent() {
    console.log("判断index来执行数据操作" + index);
    switch (index) {
        case 0:
            //学生列表页面
            console.log("准备请求网络");
            fetchStudentsList();
            break;
        case 3:
            //管理员界面
            fetchUserList();
            break;
        default:
    }
}

//获取学生列表数据
function fetchStudentsList() {
    console.log("开始请求学生列表");
    let url = '/StudentsManager/studentList';
    const net = new NetClient();
    var params = {
        "page" : page,
        "pageSize" : perPage
    };
    net.requestUrl(url, "POST", params, (error, response) => {
        if (error) {
            console.log(error);
        }
        else {
            if (response.errorCode === 0) {
                console.log("获取学生列表数据成功");
                var result = response.result;
                if (result != null) {
                    var students = result.data;
                    var total = result.total;
                    console.log("response: " + result.toString());
                    totalPage = Math.ceil(total/perPage);
                    renderPaginator(total);
                    renderStudentTable(students);
                }
            }
            else {
                console.log("获取学生列表数据失败");
            }
        }
    })
}

//index=3时用到的，请求管理员列表
function  fetchUserList() {
    console.log("开始请求用户列表");
    let url = '/StudentsManager/dbuserlist';
    const net = new NetClient();
    var params = {};
    net.requestUrl(url, "POST", params, (error, response) => {
        if (error) {
            console.log(error);
        }
        else {
            if (response.errorCode === 0) {
                console.log("获取用户列表数据成功 RESPONSE\n" + JSON.stringify(response));
                var result = response.result;
                if (result != null) {
                    var users = result;
                    createDBUserArea(users);
                }
            }
            else {
                console.log("获取用户列表数据失败");
            }
        }
    })
}

/*
    点击登出按钮
 */
function onClickExit() {
    var isExit = confirm("是否确认退出登录状态？");
    if (isExit) {
        let url = '/StudentsManager/logout';
        const net = new NetClient();
        net.requestUrl(url, 'POST', {}, (error, response) => {
            if (error) {
                console.log(error);
            } else {
                if (response.errorCode === 0) {
                    //登录成功以后才跳转页面
                    console.log("登出成功");
                } else {
                    console.log("登出失败");
                }
                //无论成功还是失败，都跳转回登录页面
                window.location.href = "/StudentsManager/Login.html";
            }
        });
    }
}

//创建管理员用户的列表，需要传入网络请求得到的管理员用户数组，json格式
function createDBUserArea(users) {
    var contetnArea = document.getElementById("contentArea");
    var html = "";
    html+='<div class="table-container">\n' +
        '  <table>\n' +
        '    <thead>\n' +
        '      <tr>\n' +
        '        <th>序号</th>\n' +
        '        <th>用户名</th>\n' +
        '        <th>管理组</th>\n' +
        '        <th>最后登录时间</th>\n' +
        '      </tr>\n' +
        '    </thead>\n' +
        //这里创建id为userTableBody的tbody，留空，在下面装载具体内容
        '    <tbody id="userTableBody">\n' +

        '    </tbody>\n' +
        '  </table>\n' +
        '</div>';
    contetnArea.innerHTML = html;
    //往tbody中填充内容
    var tbody = document.getElementById("userTableBody");
    //如果之前有数据，清空
    while (tbody.firstChild) {
        tbody.removeChild(tbody.firstChild);
    }
    for (var i = 0; i < users.length; i++) {
        var user = users[i];
        var tr = document.createElement("tr");
        // 使用自定义属性保存学生对象
        var groupstr = "未知";
        if (user.group === "a") {
            groupstr = "超级管理";
        }
        tr.innerHTML = "<td>" + user.id + "</td>" +
            "<td>" + user.name + "</td>" +
            "<td>" + groupstr + "</td>" +
            "<td>" + user.tokentime + "</td>";
        tbody.appendChild(tr);
    }
}

//学生列表的表头
function createStudentTableHeader() {
    var contetnArea = document.getElementById("contentArea");
    var html = "";
    if (index === 2) {
        //添加搜索框
        html += createSearchContent();
    }
    html += '<table id="studentTable">\n' +
        '        <thead>\n' +
        '        <tr>\n' +
        '            <th>学号</th>\n' +
        '            <th>姓名</th>\n' +
        '            <th>性别</th>\n' +
        '            <th>出生日期</th>\n' +
        '            <th>邮箱</th>\n' +
        '            <th>备注</th>\n' +
        '            <th>操作</th>\n' +
        '        </tr>\n' +
        '        </thead>\n' +
        '        <tbody id = "studentTableBody">\n' +
        '<!--        动态生成学生数据-->\n' +
        '        </tbody>\n' +
        '    </table>\n' +
        '    <div id="nodata" style="display: none">暂无数据</div>\n' +
        '    <nav align="center">\n' +
        '        <ul id="paginator" class="pagination">\n' +
        '<!--            分页按钮区域-->\n' +
        '        </ul>\n' +
        '    </nav>';
    contetnArea.innerHTML = html;
}

//当页面是搜索时，这里写的是绘制一个搜索框的html
function createSearchContent() {
    var html = '<div class="search-input">\n' +
        '        <input type="text" placeholder="请输入搜索内容">\n' +
        '        <select>\n' +
        '            <option value="stuNumber">学号</option>\n' +
        '            <option value="stuName">姓名</option>\n' +
        '            <option value="sex">性别</option>\n' +
        '            <option value="birthday">出生日期</option>\n' +
        '            <option value="email">邮箱</option>\n' +
        '            <option value="notes">备注</option>\n' +
        '        </select>\n' +
        '        <button onclick="search()">搜索</button>\n' +
        '    </div>';
    return html;
}

//准备发起搜索学生的网络请求, type有多种，即数据库里学生信息的各个字段
function search() {
    var keyword = document.querySelector('.search-input input[type="text"]').value;
    var type = document.querySelector('.search-input select').value;
    // 发起网络请求
    console.log('搜索内容：' + keyword + '，搜索类型：' + type);
    var data = {
        "type" : type,
        "keyword" : keyword
    };
    requestSearchStudents(data);
}

//发起搜搜学生的网络请求
function requestSearchStudents(data) {
    let url = '/StudentsManager/studentList';
    const net = new NetClient();
    var params = {
        "page" : 1,
        "pageSize" : perPage,
        "searchColumn" : data.type,
        "searchValue" : data.keyword
    };
    net.requestUrl(url, "POST", params, (error, response) => {
        if (error) {
            console.log(error);
        }
        else {
            if (response.errorCode === 0) {
                console.log("获取学生列表数据成功");
                var result = response.result;
                if (result != null) {
                    var students = result.data;
                    for (var i=0; i< students.length; i++) {
                        console.log(students[i].email);
                    }
                    var total = result.total;
                    console.log("response: " + result.toString());
                    totalPage = Math.ceil(total/perPage);
                    // 调用绘制学生列表的方法，把搜索到的学生数组传给它
                    renderStudentTable(students);
                }
            }
            else {
                console.log("获取学生列表数据失败");
            }
        }
    })
}

//绘制新增学生的页面
function createNewStudentArea() {
    var contetnArea = document.getElementById("contentArea");
    var html = "";
    html += '<form id="student-form">\n' +
        '        <div>\n' +
        '            <label for="id">学号：</label>\n' +
        '            <input type="text" id="id" name="id" value="" required>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="name">姓名：</label>\n' +
        '            <input type="text" id="name" name="name" value="" required>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="gender">性别：</label>\n' +
        '            <input type="radio" id="gender-male" name="gender" value="male" checked>\n' +
        '            <label for="gender-male">男</label>\n' +
        '            <input type="radio" id="gender-female" name="gender" value="female">\n' +
        '            <label for="gender-female">女</label>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="birthday">生日：</label>\n' +
        '            <input type="date" id="birthday" name="birthday" value="1999-01-01" required>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="email">邮箱：</label>\n' +
        '            <input type="email" id="email" name="email" value="" required>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="remark">备注：</label>\n' +
        '            <textarea id="remark" name="remark" value="" rows="5" cols="30" maxlength="200"></textarea>\n' +
        '        </div>\n' +
        '        <div id="editEndButton">\n' +
        '            <button type="button" onclick="submitNewStudentForm()">提交</button>\n' +
        '        </div>';
    contetnArea.innerHTML = html;
}

//绘制编辑学生页面，与新增学生大部分相似，主要是有学生的旧信息，点击提交调用的方法也不同
function createEditStudentArea(student) {
    if (student === null) return;
    var contetnArea = document.getElementById("contentArea");
    var isMale = student.sex === "男" ? "checked" : "";
    var isFemale = student.sex === "男" ? "" : "checked";
    var birthday = student.birthday;
    console.log("获取学生生日" + birthday);
    console.log("学生备注" + student.notes);
    var html = "";
    html += '<form id="student-form">\n' +
        '        <div>\n' +
        '            <label for="id">学号：</label>\n' +
        '            <input type="text" id="id" name="id" readonly value="' + student.stuNumber + '" required>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="name">姓名：</label>\n' +
        '            <input type="text" id="name" name="name" value="' + student.stuName + '" required>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="gender">性别：</label>\n' +
        '            <input type="radio" id="gender-male" name="gender" value="male" ' + isMale + '>\n' +
        '            <label for="gender-male">男</label>\n' +
        '            <input type="radio" id="gender-female" name="gender" value="female" ' + isFemale + '>\n' +
        '            <label for="gender-female">女</label>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="birthday">生日：</label>\n' +
        '            <input type="date" id="birthday" name="birthday" value="' + birthday + '" required>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="email">邮箱：</label>\n' +
        '            <input type="email" id="email" name="email" value="'+ student.email +'" required>\n' +
        '        </div>\n' +
        '        <div>\n' +
        '            <label for="remark">备注：</label>\n' +
        '            <textarea id="remark" name="remark" rows="5" cols="30" maxlength="200">' + student.notes + '</textarea>\n' +
        '        </div>\n' +
        '        <div id="editEndButton">\n' +
        '            <button type="button" onclick="submitEditStudentForm()">提交</button>\n' +
        '            <button type="button" onclick="cancelEdit()">取消</button>\n' +
        '        </div>';
    contetnArea.innerHTML = html;
}

//取消编辑，这里简单调用了个刷新页面，有需求再改
function cancelEdit() {
    //刷新页面即可
    location.reload();
}

//提交编辑学生的请求，获取表单元素的值
function submitEditStudentForm() {
// 获取表单元素
    console.log("tap submit event ...");
    var form = document.getElementById('student-form');
    // 获取表单数据
    var data = {
        stuNumber: form.id.value.trim(),
        stuName: form.name.value.trim(),
        sex: form.gender.value === "male" ? "男" : "女",
        birthday: form.birthday.value.trim(),
        email: form.email.value.trim(),
        notes: form.remark.value.trim()
    };
    // 检查表单数据是否合法
    if (validateForm(data)) {
        console.log('表单数据合法，可以提交。 data:' + data);
        requestEditStudent(data);
    }
}

//发起编辑学生的请求，得到返回后回到学生列表
function requestEditStudent(params) {
    let url = '/StudentsManager/editStudent';
    const net = new NetClient();
    net.requestUrl(url, "POST", params, (error, response) => {
        if (error) {
            console.log(error);
        }
        else {
            if (response.errorCode === 0) {
                console.log("编辑学生数据成功");
                //切换回学生列表页面
                if (window.confirm('编辑学生数据成功！')) {
                    window.location.href = '/StudentsManager/welcome.html?index=0';
                }
            }
            else {
                var msg = response.message;
                if (window.confirm('编辑学生数据失败！' + msg)) {
                }
            }
        }
    })
}

//提交新建学生的请求
function submitNewStudentForm() {
    // 获取表单元素
    console.log("tap submit event ...");
    var form = document.getElementById('student-form');
    // 获取表单数据
    var data = {
        stuNumber: form.id.value.trim(),
        stuName: form.name.value.trim(),
        sex: form.gender.value === "male" ? "男" : "女",
        birthday: form.birthday.value.trim(),
        email: form.email.value.trim(),
        notes: form.remark.value.trim()
    };
    // 检查表单数据是否合法
    if (validateForm(data)) {
        console.log('表单数据合法，可以提交。 data:' + data);
        requetNewStrudent(data);
    }
}

//发起新建学生的请求
function requetNewStrudent(params) {
    let url = '/StudentsManager/newStudent';
    const net = new NetClient();
    console.log("正在请求新增学生");
    net.requestUrl(url, "POST", params, (error, response) => {
        if (error) {
            console.log(error);
        }
        else {
            if (response.errorCode === 0) {
                console.log("新建学生数据成功");
                //切换回学生列表页面
                if (window.confirm('新增学生成功！')) {
                    window.location.href = '/StudentsManager/welcome.html?index=0';
                }
            }
            else {
                var msg = response.message;
                if (window.confirm('新增学生失败！' + msg)) {
                }
            }
        }
    })
}

//验证输入的学生信息是否正确
function validateForm(data) {
    if (!data.stuNumber) {
        alert("请输入学号");
        return false;
    }
    if (!data.stuName) {
        alert('请输入姓名。');
        return false;
    }
    if (!data.email) {
        alert('请输入邮箱。');
        return false;
    }
    return true;
}

//配置顶部导航条各个按钮的点击事件
function addEventToTopArea() {
    var navList = document.querySelectorAll('.nav-li');
    navList[0].addEventListener('click', function (event) {
        //学生一览，重新加载
        event.defaultPrevented;
        window.location.href = "/StudentsManager/welcome.html?index=0";
    });
    navList[1].addEventListener('click', function (event) {
        //新增学生页面
        event.defaultPrevented;
        window.location.href = "/StudentsManager/welcome.html?index=1";
    });
    navList[2].addEventListener('click', function (event) {
        //查找学生页面
        event.defaultPrevented;
        window.location.href = "/StudentsManager/welcome.html?index=2";
    });
    navList[3].addEventListener('click', function (event) {
        //管理员页面
        event.defaultPrevented;
        window.location.href = "/StudentsManager/welcome.html?index=3";
    });
    navList[4].addEventListener('click', function () {
        //退出登录
        onClickExit();
        return false;
    });
}

//为学生列表的页码添加事件
function addEventToPageArea() {
    if (index === 0 || index === 2) {
        var paginator = document.getElementById("paginator");
        console.log("load complete...paginator = " + paginator);
        paginator.addEventListener("click", function (event) {
            console.log("点击事件");
            event.preventDefault();
            if (event.target.tagName !== "A") return;
            var newPage = parseInt(event.target.dataset.page);
            if (newPage !== page) {
                if (newPage < 1) newPage = 1;
                if (newPage > totalPage) newPage = totalPage;
                page = newPage;
                console.log("新页码=" + page);
                fetchStudentsList();
            }
        });
    }
}

//渲染页码区域
function renderPaginator(amount) {
    var paginator = document.getElementById("paginator");
    console.log("amount is " + amount);
    console.log("paginator:" + paginator);
    var totalPages = Math.ceil(amount/perPage);
    var html = "";
    // 添加上一页按钮
    html += '<li class="page-item"><a class="page-link" href="#" data-page="' + (page - 1) + '">上一页</a></li>';
    // 当总页数小于等于7时，渲染所有页码按钮
    if (totalPages <= 7) {
        for (var i = 1; i <= totalPages; i++) {
            if (i === page) {
                html += '<li class="page-item active"><a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>';
            } else {
                html += '<li class="page-item"><a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>';
            }
        }
    }
    // 当总页数大于7时，只渲染当前页码和上一页、下一页按钮
    else {
        if (page === 1) {
            html += '<li class="page-item active"><a class="page-link" href="#" data-page="1">1</a></li>';
            html += '<li class="page-item"><a class="page-link" href="#" data-page="2">2</a></li>';
        } else if (page === totalPages) {
            html += '<li class="page-item"><a class="page-link" href="#" data-page="' + (totalPages - 1) + '">' + (totalPages - 1) + '</a></li>';
            html += '<li class="page-item active"><a class="page-link" href="#" data-page="' + totalPages + '">' + totalPages + '</a></li>';
        } else {
            html += '<li class="page-item"><a class="page-link" href="#" data-page="' + (page - 1) + '">' + (page - 1) + '</a></li>';
            html += '<li class="page-item active"><a class="page-link" href="#" data-page="' + page + '">' + page + '</a></li>';
            html += '<li class="page-item"><a class="page-link" href="#" data-page="' + (page + 1) + '">' + (page + 1) + '</a></li>';
        }
    }
    // 添加下一页按钮
    html += '<li class="page-item"><a class="page-link" href="#" data-page="' + (page + 1) + '">下一页</a></li>';
    paginator.innerHTML = html; // 渲染分页导航条
}

//渲染学生列表
function renderStudentTable(students) {
    var tbody = document.getElementById("studentTableBody");
    // 判断数据是否为空
    if (students.length === 0) {
        document.getElementById("nodata").style.display = "block"; // 显示提示信息
        tbody.style.display = "none"; // 隐藏表格
    } else {
        document.getElementById("nodata").style.display = "none"; // 隐藏提示信息
        tbody.style.display = "table-row-group"; // 显示表格
        // 删除之前的学生数据
        while (tbody.firstChild) {
            tbody.removeChild(tbody.firstChild);
        }
        // 动态生成新的数据行
        for (var i = 0; i < students.length; i++) {
            var student = students[i];
            var tr = document.createElement("tr");
            // 使用自定义属性保存学生对象
            tr.setAttribute("data-student", JSON.stringify(student));
            tr.innerHTML = "<td>" + student.stuNumber + "</td>" +
                "<td>" + student.stuName + "</td>" +
                "<td>" + student.sex + "</td>" +
                "<td>" + student.birthday + "</td>" +
                "<td>" + student.email + "</td>" +
                "<td>" + student.notes + "</td>" +
                "<td><a href='javascript:;' class='editBtn'>编辑</a> <a href='javascript:;' class='delBtn'>删除</a></td>";
            tbody.appendChild(tr);

            // 编辑按钮的事件
            var editBtn = tr.querySelector(".editBtn");
            editBtn.onclick = function () {
                var student = JSON.parse(this.parentNode.parentNode.getAttribute("data-student"));
                createEditStudentArea(student);
            }
            // 给删除按钮添加点击事件
            var delBtn = tr.querySelector(".delBtn");
            delBtn.onclick = function() {
                // 获取所属行的学生对象
                var student = JSON.parse(this.parentNode.parentNode.getAttribute("data-student"));
                var isDelete = confirm("是否确认删除[学号:" + student.stuNumber + "]" + student.stuName + "的相关信息?");
                if (isDelete) {
                    requestDeleteStudent(student);
                }
            };
        }
    }
}

//删除学生
function requestDeleteStudent(student) {
    let url = '/StudentsManager/deleteStudent';
    const net = new NetClient();
    console.log("正在请求删除学生");
    net.requestUrl(url, "POST", student, (error, response) => {
        if (error) {
            console.log(error);
        }
        else {
            if (response.errorCode === 0) {
                console.log("删除学生数据成功");
                //切换回学生列表页面
                if (window.confirm('删除学生成功！')) {
                    window.location.href = '/StudentsManager/welcome.html?index=0';
                }
            }
            else {
                var msg = response.message;
                if (window.confirm('删除学生失败！' + msg)) {
                }
            }
        }
    })
}